package com.example.controller;

import ch.qos.logback.core.util.MD5Util;
import ch.qos.logback.core.util.StringUtil;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import com.example.utils.Md5Util;
import com.example.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{2,5}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {

//        查询用户是否存在
        User u = userService.findByUserName(username);
        if (u == null) {
//           没有占用,注册
            userService.register(username, password);
            return Result.success();
        } else {
//            占用

        }

        return Result.error("用户名被占用");

    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{2,5}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
//        根据用户名查询用户
        User loginUser = userService.findByUserName(username);
//                判断该用户是否存在
        if (loginUser == null) {
            return Result.error("用户名不存在");
        }
//        判断密码是否正常 因数据库中的password密码是密文 可以先把输入的密码进行加密，然后跟数据库中的比较
//        loginUser.getPassword())这个是数据库中的密文
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            //           登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
//            把token存入到redis当中
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set(token,token,1, TimeUnit.DAYS);
//            token给data
            return Result.success(token);
        }


        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
//    通过用户token 进行解析获取username
    public Result<User> userinfo() {
//        根据用户查询用户
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
//        这个解析了token
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);

        return Result.success(user);

    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();

    }

    @PatchMapping("/updatePwd")
//    @RequestBody mvc框架会把json格式的数据转换成map格式的对象
    public Result updatePwd(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token) {
//        1.效验参数
        String old_pwd = params.get("old_pwd");
        String new_pwd = params.get("new_pwd");
        String re_pwd = params.get("re_pwd");

        if (!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)) {
            return Result.error("缺少必要的参数");
        }
//        原密码是否正确
//        调用userservice获取的原密码，和oldpwd比较
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
//       Md5Util.getMD5String(old_pwd)是对密码加密
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(old_pwd))) {
            return Result.error("原密码不正确");
        }
//       判断新密码和确认密码是否一样
        if (!re_pwd.equals(new_pwd)) {
            return Result.error("俩次填写的密码不一致");

        }


//        2.调用service更新密码
        userService.updatePwd(new_pwd);
//        删除redis中的token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return Result.success();


    }


}
